import { request, post, get } from '@/utils/request.ts';

// ==================== 聊天相关接口 ====================

/**
 * 获取用户会话列表
 * @param page 页码（默认0）
 * @param size 每页大小（默认20）
 */
export const getChatConversations = (page = 0, size = 20, type = null) => {
    // 从本地存储获取用户ID
    const userInfoStr = localStorage.getItem('userInfo');
    let userId = '';

    if (userInfoStr) {
        try {
            const userInfo = JSON.parse(userInfoStr);
            userId = userInfo.id || '';
        } catch (error) {
            console.error('解析用户信息失败', error);
        }
    }

    // 构建查询参数
    let queryParams = `page=${page}&size=${size}&userId=${userId}`;

    // 如果传入了type参数，添加到查询字符串中
    if (type && (type === 'private' || type === 'group')) {
        queryParams += `&type=${type}`;
    }

    return get(`/api/chat/conversations?${queryParams}`);
};

/**
 * 获取会话详情
 * @param conversationId 会话ID
 */
export const getChatConversationDetail = (conversationId: number) => {
    const userInfoStr = localStorage.getItem('userInfo');
    let userId = '';

    if (userInfoStr) {
        try {
            const userInfo = JSON.parse(userInfoStr);
            userId = userInfo.id || '';
        } catch (error) {
            console.error('解析用户信息失败', error);
        }
    }

    return get(`/api/chat/conversations/${conversationId}?userId=${userId}`);
};

/**
 * 创建私聊会话
 * @param targetUserId 目标用户ID
 */
export const createPrivateConversation = (targetUserId: number) => {
    const userInfoStr = localStorage.getItem('userInfo');
    let userId = '';

    if (userInfoStr) {
        try {
            const userInfo = JSON.parse(userInfoStr);
            userId = userInfo.id || '';
        } catch (error) {
            console.error('解析用户信息失败', error);
        }
    }

    return post(`/api/chat/conversations/private?targetUserId=${targetUserId}&userId=${userId}`);
};

/**
 * 创建群聊会话
 * @param request 创建群聊请求数据
 */
export const createGroupConversation = (request: {
    title: string;
    participantIds: number[];
}) => {
    const userInfoStr = localStorage.getItem('userInfo');
    let userId = '';

    if (userInfoStr) {
        try {
            const userInfo = JSON.parse(userInfoStr);
            userId = userInfo.id || '';
        } catch (error) {
            console.error('解析用户信息失败', error);
        }
    }

    return post(`/api/chat/conversations/group?userId=${userId}`, request);
};

/**
 * 发送消息
 * @param request 发送消息请求数据
 */
export const sendChatMessage = (request: {
    conversationId: number;
    messageType?: string;
    content: string;
}) => {
    const userInfoStr = localStorage.getItem('userInfo');
    let userId = '';

    if (userInfoStr) {
        try {
            const userInfo = JSON.parse(userInfoStr);
            userId = userInfo.id || '';
        } catch (error) {
            console.error('解析用户信息失败', error);
        }
    }

    return post(`/api/chat/messages?userId=${userId}`, request);
};

/**
 * 获取聊天记录
 * @param conversationId 会话ID
 * @param page 页码（默认0）
 * @param size 每页大小（默认50）
 */
export const getChatMessages = (conversationId: number, page = 0, size = 50) => {
    const userInfoStr = localStorage.getItem('userInfo');
    let userId = '';

    if (userInfoStr) {
        try {
            const userInfo = JSON.parse(userInfoStr);
            userId = userInfo.id || '';
        } catch (error) {
            console.error('解析用户信息失败', error);
        }
    }

    return get(`/api/chat/conversations/${conversationId}/messages?page=${page}&size=${size}&userId=${userId}`);
};

/**
 * 标记消息为已读
 * @param conversationId 会话ID
 */
export const markChatMessagesAsRead = (conversationId: number) => {
    const userInfoStr = localStorage.getItem('userInfo');
    let userId = '';

    if (userInfoStr) {
        try {
            const userInfo = JSON.parse(userInfoStr);
            userId = userInfo.id || '';
        } catch (error) {
            console.error('解析用户信息失败', error);
        }
    }

    return post(`/api/chat/conversations/${conversationId}/read?userId=${userId}`);
};

/**
 * 添加参与者到群聊
 * @param conversationId 会话ID
 * @param request 添加参与者请求数据
 */
export const addChatParticipants = (conversationId: number, request: {
    userIds: number[];
    role?: string;
}) => {
    const userInfoStr = localStorage.getItem('userInfo');
    let userId = '';

    if (userInfoStr) {
        try {
            const userInfo = JSON.parse(userInfoStr);
            userId = userInfo.id || '';
        } catch (error) {
            console.error('解析用户信息失败', error);
        }
    }

    return post(`/api/chat/conversations/${conversationId}/participants?userId=${userId}`, request);
};

/**
 * 获取未读消息总数
 */
export const getUnreadMessageCount = () => {
    const userInfoStr = localStorage.getItem('userInfo');
    let userId = '';

    if (userInfoStr) {
        try {
            const userInfo = JSON.parse(userInfoStr);
            userId = userInfo.id || '';
        } catch (error) {
            console.error('解析用户信息失败', error);
        }
    }

    return get(`/api/chat/unread/count?userId=${userId}`);
};


// ==================== 教师相关接口 ====================
export const getTeacherDashboard = () => {
    const userInfoStr = localStorage.getItem('userInfo');
    let userId = '';

    if (userInfoStr) {
        try {
            const userInfo = JSON.parse(userInfoStr);
            userId = userInfo.id || '';
        } catch (error) {
            console.error('解析用户信息失败', error);
        }
    }

    return get('/api/teacher/dashboard?userId=' + userId);
};

export const fetchTeacherClasses = (teacherId: number) => {
    return get(`/api/classes/by-teacher?teacherId=${teacherId}`);
};

// ==================== 排课相关接口 ====================
export const fetchTeacherScheduleByDateRange = (
    teacherId: number,
    classId: number,
    startDate: string,  // 格式: YYYY-MM-DD
    endDate: string     // 格式: YYYY-MM-DD
) => {
    const params = new URLSearchParams();
    params.append('teacherId', teacherId.toString());
    params.append('classId', classId.toString());
    params.append('startDate', startDate);
    params.append('endDate', endDate);

    return get(`/api/schedules?${params.toString()}`);
};

export const changeSchedules = (scheduleId: number, specificDate: string, timeSlotId: number) => {
    return post(`/api/schedules/${scheduleId}/reschedule`, {
        specificDate,
        timeSlotId
    });
};

// ==================== 学期和周期相关接口 ====================
export const fetchAllTerms = () => {
    return get('/api/terms');
};

export const fetchTermWeeks = (termId: number, startDay = 1) => {
    return get(`/api/weeks/by-term?termId=${termId}&startDay=${startDay}`);
};

export const fetchAllTermsForStudents = () => {
    return get('/api/students/terms');
};

// ==================== 学生相关接口 ====================
export const fetchAllGrades = () => {
    return get('/api/students/grades');
};

export const fetchStudentsByCriteria = (teacherId: number, termId?: number, gradeLevel?: string) => {
    const params = new URLSearchParams();
    params.append('teacherId', teacherId.toString());

    if (termId) {
        params.append('termId', termId.toString());
    }
    if (gradeLevel) {
        params.append('gradeLevel', gradeLevel);
    }

    return get(`/api/students?${params.toString()}`);
};

// ==================== 主题和子主题相关接口 ====================
export const fetchThemes = () => {
    return get(`/api/themes`);
};

export const createSubTheme = (data: any) => {
    return post('/api/themes/sub-themes', data);
};

export const getThemeWithAllSubThemes = (parentId: number) => {
    return get(`/api/themes/details?parentId=${parentId}`);
};

// ==================== 课程相关接口 ====================
export const fetchCourseCategories = () => {
    return get('/api/courses/categories');
};

export const createActivity = (activityData: {
    category: string;
    activityName: string;
    classroomId: number;
    specificDate: string;
    timeSlotId: number;
    teacherId: number;
    termId: number;
    classId: number;
}) => {
    return post('/api/schedules/activities', activityData);
};

// ==================== 教学资源相关接口 ====================
export const fetchTeachingMenu = () => {
    return get('/api/teaching-resources/menu');
};

export const fetchResourceTypes = () => {
    return get('/api/teaching-resources/types');
};

export const fetchResources = (params: {
    subcategoryId: number;
    typeId: number;
    keyword: string;
}) => {
    return post('/api/teaching-resources/list', params);
};

// ==================== 活动记录相关接口 ====================
export const fetchRecordings = () => {
    return get(`/api/recordings`);
};

export const fetchExtracurricularRecordings = (params: {
    termId?: number;
    classId?: number;
}) => {
    const queryParams = new URLSearchParams();

    if (params.termId) {
        queryParams.append('termId', params.termId.toString());
    }

    if (params.classId) {
        queryParams.append('classId', params.classId.toString());
    }

    return get(`/api/extracurricular-recordings?${queryParams.toString()}`);
};

export const fetchCategories = () => {
    return get(`/api/activities/categories`);
};

// teacher.ts - 添加创建活动接口
export const createUserActivity = (activityData: any) => {
    return post('/api/user-activities/create', activityData);
};

// ==================== 用户活动相关接口 ====================
export const activitiesByDate = (date: any) => {
    const userInfoStr = localStorage.getItem('userInfo');
    let userId = '';

    if (userInfoStr) {
        try {
            const userInfo = JSON.parse(userInfoStr);
            userId = userInfo.id || '';
        } catch (error) {
            console.error('解析用户信息失败', error);
        }
    }

    return get('/api/user-activities/by-date?userId=' + userId + '&date=' + date);
};

export const statusByDate = (date: any) => {
    const userInfoStr = localStorage.getItem('userInfo');
    let userId = '';

    if (userInfoStr) {
        try {
            const userInfo = JSON.parse(userInfoStr);
            userId = userInfo.id || '';
        } catch (error) {
            console.error('解析用户信息失败', error);
        }
    }

    return get('/api/user-activities/daily-status?userId=' + userId + '&date=' + date);
};

export const activitiesCheckin = (activityId: any, params: any) => {
    return request({
        url: `/api/user-activities/checkin?activityId=${activityId}`,
        method: 'POST',
        data: params,
    });
};

// ==================== 活动基地相关接口 ====================
export const getActivityBases = () => {
    return get(`/api/activity-bases`);
};

// ==================== 活动列表相关接口 ====================
export const getAllActivities = (userId: number, keyword?: string, baseId?: string, fee?: string) => {
    const params: any = { userId };
    if (keyword) params.keyword = keyword;
    if (baseId) params.baseId = baseId;
    if (fee) params.fee = fee;

    return get('/api/user-activities/list', params);
};

export const getJoinedActivities = (userId: number, keyword?: string, baseId?: string, fee?: string) => {
    const params: any = { userId };
    if (keyword) params.keyword = keyword;
    if (baseId) params.baseId = baseId;
    if (fee) params.fee = fee;
    return get('/api/user-activities/joined', params);
};

// teacher.ts - 添加我发布的接口
export const getPublishedActivities = (userId: number, keyword?: string, baseId?: string, fee?: string) => {
    const params: any = { userId };
    if (keyword) params.keyword = keyword;
    if (baseId) params.baseId = baseId;
    if (fee) params.fee = fee;

    return get('/api/user-activities/published', params);
};

// ==================== 新增：活动报名接口 ====================
export const signupActivity = (userId: number, activityId: number) => {
    return post(`/api/user-activities/signup?userId=${userId}&activityId=${activityId}`);
};

export const cancelSignupActivity = (userId: number, activityId: number) => {
    return post('/api/user-activities/cancel-signup', { userId, activityId });
};

// ==================== 文件上传相关接口 ====================
export const uploadFile = (file: File) => {
    const formData = new FormData();
    formData.append('file', file);

    return request({
        url: '/api/upload/file',
        method: 'POST',
        data: formData,
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    });
};

export const uploadImage = (image: File) => {
    const formData = new FormData();
    formData.append('image', image);

    return request({
        url: '/api/upload/image',
        method: 'POST',
        data: formData,
    });
};

export const uploadVideo = (video: File) => {
    const formData = new FormData();
    formData.append('video', video);

    return request({
        url: '/api/upload/video',
        method: 'POST',
        data: formData,
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    });
};

// ==================== 侧边栏数据接口 ====================
export const getSidebarData = () => {
    return get('/api/sidebar');
};

// ==================== 通知相关接口 ====================

/**
 * 获取通知列表
 * @param userId 用户ID
 * @param tabType 标签类型："received"(收到的) 或 "published"(发布的)
 * @param typeId 通知类型ID（可选）
 * @param page 页码（可选，默认1）
 * @param size 每页大小（可选，默认10）
 */
export const fetchNotices = (
    userId: number,
    tabType: 'received' | 'published',
    typeId?: number,
    page?: number,
    size?: number
) => {
    const params: any = {
        userId,
        tabType
    };

    if (typeId) params.typeId = typeId;
    if (page) params.page = page;
    if (size) params.size = size;

    return get('/api/notices', params);
};

/**
 * 获取所有通知类型
 */
export const fetchNoticeTypes = () => {
    return get('/api/notices/types');
};

/**
 * 标记通知为已读
 * @param noticeId 通知ID
 * @param userId 用户ID
 */
export const markNoticeAsRead = (noticeId: number, userId: number) => {
    return post(`/api/notices/${noticeId}/read?userId=${userId}`);
};

/**
 * 创建通知
 * @param noticeData 通知数据
 */
export const createNotice = (noticeData: any, userId: number) => {
    return post(`/api/notices?userId=${userId}`, noticeData);
};

/**
 * 更新通知
 * @param noticeId 通知ID
 * @param noticeData 通知数据
 */
export const updateNotice = (noticeId: number, noticeData: any, userId: number) => {
    return post(`/api/notices/${noticeId}?userId=${userId}`, noticeData);
};

/**
 * 删除通知
 * @param noticeId 通知ID
 */
export const deleteNotice = (noticeId: number, userId: number) => {
    return request({
        url: `/api/notices/${noticeId}?userId=${userId}`,
        method: 'DELETE'
    });
};

/**
 * 获取通知详情
 * @param noticeId 通知ID
 * @param tabType 标签类型（用于确定显示哪些额外信息）
 */
export const fetchNoticeDetail = (noticeId: number, tabType: 'received' | 'published') => {
    return get(`/api/notices/${noticeId}?tabType=${tabType}`);
};

/**
 * 获取班级选项（用于通知接收对象选择）
 */
export const fetchClassOptions = () => {
    return get('/api/classes/options');
};

/**
 * 获取用户选项（用于通知接收对象选择）
 * @param keyword 搜索关键词（可选）
 */
export const fetchUserOptions = (keyword?: string, role?: string, classId?: number) => {
    const params: any = {};
    if (keyword) params.keyword = keyword;
    if (role) params.role = role;
    if (classId) params.classId = classId;
    return get('/api/users/options', params);
};

/**
 * 获取课程选项（用于关联课程选择）
 */
export const fetchScheduleOptions = (teacherId?: number, classId?: number) => {
    const params: any = {};
    if (teacherId) params.teacherId = teacherId;
    if (classId) params.classId = classId;
    return get('/api/schedules/options', params);
};

// ==================== 新增：活动详情接口 ====================

/**
 * 根据活动ID获取活动详情
 * @param activityId 活动ID
 * @param userId 用户ID（可选，用于检查是否已报名）
 */
export const getActivityDetail = (activityId: number, userId?: number) => {
    const params: any = { activityId };
    if (userId) params.userId = userId;
    return get(`/api/user-activities/details`, params);
};

/**
 * 自动获取用户信息并调用活动详情接口
 * @param activityId 活动ID
 */
export const getActivityDetailWithAutoUser = (activityId: number) => {
    const userInfoStr = localStorage.getItem('userInfo');
    let userId: number | undefined;

    if (userInfoStr) {
        try {
            const userInfo = JSON.parse(userInfoStr);
            userId = userInfo.id ? parseInt(userInfo.id) : undefined;
        } catch (error) {
            console.error('解析用户信息失败', error);
        }
    }

    return getActivityDetail(activityId, userId);
};

/**
 * 获取今日活动列表（使用本地存储的用户ID）
 */
export const getTodayActivities = () => {
    const userInfoStr = localStorage.getItem('userInfo');
    let userId = '';

    if (userInfoStr) {
        try {
            const userInfo = JSON.parse(userInfoStr);
            userId = userInfo.id || '';
        } catch (error) {
            console.error('解析用户信息失败', error);
        }
    }

    return get('/api/user-activities/today?userId=' + userId);
};

// ==================== 通讯录相关接口 ====================

/**
 * 获取包含年级信息的完整班级列表
 */
export const fetchClassesWithGrades = () => {
    return get('/api/classes');
};

/**
 * 获取所有年级列表（从班级接口获取）
 */
export const fetchGradeList = () => {
    return get('/api/classes/grades');
};

/**
 * 根据年级获取班级列表
 * @param gradeLevel 年级名称，如"一年级"
 */
export const fetchClassesByGrade = (gradeLevel: string) => {
    return get(`/api/classes/by-grade?gradeLevel=${encodeURIComponent(gradeLevel)}`);
};

/**
 * 获取通讯录层级数据（年级-班级-学生）
 */
export const fetchContactHierarchy = () => {
    return get('/api/contacts/hierarchy');
};

/**
 * 获取所有老师列表
 */
export const fetchAllTeachers = () => {
    return get('/api/users/teachers');
};

/**
 * 搜索老师
 * @param keyword 搜索关键词
 */
export const searchTeachers = (keyword?: string) => {
    const params: any = {};
    if (keyword) params.keyword = keyword;
    return get('/api/users/teachers/search', params);
};
